<template>
  <scroll-view scroll-y="ture" style="height: 100vh">
    <template v-if="activityStatus === '活动中'">
      <view
        class="ultraman-container"
        :style="{
          backgroundImage: `url(${oss2('others/ultraman/index_bg.png')})`,
        }"
      >
        <view
          class="rule_icon icon_btn"
          @click.stop="openRule"
          :style="{
            backgroundImage: `url(${oss2('others/ultraman/rule_icon.png')})`,
          }"
        ></view>
        <view
          class="prize_icon icon_btn"
          :style="{
            backgroundImage: `url(${oss2('others/ultraman/prize_icon.png')})`,
          }"
          @click.stop="toPrize"
        >
        </view>
        <view
          class="card_icon icon_btn"
          @click.stop="toCard"
          :style="{
            backgroundImage: `url(${oss2('others/ultraman/card_icon.png')})`,
          }"
          ><view class="signal" v-if="showCard"></view>
        </view>

        <view
          class="code_btn index_btn"
          @click.stop="toScanCode"
          :style="{
            backgroundImage: `url(${oss2(
              'others/ultraman/index_code_btn.png'
            )})`,
          }"
        ></view>
        <view
          class="buy_btn index_btn"
          @click.stop="toPurchase"
          :style="{
            backgroundImage: `url(${oss2(
              'others/ultraman/index_buy_btn.png'
            )})`,
          }"
        ></view>

        <view class="code_hint flex items-center justify-center">
          二维码无法识别，点我
          <view class="text_link" @click.stop="toInput">手动核销</view>
          ；如遇其他无法参与活动的情形
        </view>
        <view class="code_text">
          (如二维码错、漏、模糊等问题)，请拨打客服热线400-0880-325(周一至周五09:00-18:00，节假日除外)
        </view>
        <view class="agree flex items-center justify-center">
          <view class="i-agree" @click.stop="doAgree">
            <image v-if="iAgree" :src="oss2('others/ultraman/choose.png')" />
          </view>
          <view class="agree-content items-center">
            已阅读并同意
            <view class="text_link" @click.stop="openRule2">活动规则</view>
          </view>
        </view>

        <view
          class="ultraman_sign"
          :style="{
            backgroundImage: `url(${oss2('others/ultraman/ultraman_gs.png')})`,
          }"
        >
        </view>
      </view>
    </template>

    <template v-else>
      <view
        class="ultraman-container puzzle"
        :style="{
          backgroundImage: `url(${
            activityStatus === '未开始'
              ? oss2('others/ultraman/index_bg_wait.png')
              : activityStatus === '已结束'
              ? oss2('others/ultraman/index_bg_end.png')
              : oss2('others/ultraman/index_bg_err.png')
          })`,
        }"
      >
        <view
          class="backHomeBtn"
          @click.stop="backHome"
          :style="{
            backgroundImage: `url(${oss2('others/ultraman/index_back.png')})`,
          }"
        ></view>
        <view
          class="ultraman_sign"
          :style="{
            backgroundImage: `url(${oss2('others/ultraman/ultraman_gs.png')})`,
          }"
        >
        </view>
      </view>
    </template>

    <!-- 弹窗 -->
    <view class="mode" v-if="showDialog">
      <view
        class="Dialog_body w-375px top-21vh left-0px"
        :style="{
          backgroundImage: `url(${oss2('others/ultraman/' + dialogBg)})`,
        }"
      >
        <view class="Dialog_close" @click.stop="dialogClose"></view>
        <view
          class="Dialog_back w-168px h-58px bottom-77px left-104px"
          @click.stop="dialogBack"
          :style="{
            backgroundImage: `url(${oss2('others/ultraman/code_back.png')})`,
          }"
        ></view>
        <view
          class="Dialog_rule w-65px h-11px bottom-56px left-156px"
          @click.stop="openRule3"
          :style="{
            backgroundImage: `url(${oss2('others/ultraman/rule_check.png')})`,
          }"
        >
        </view>
      </view>
    </view>

    <!-- 活动规则弹窗 -->
    <rule-popup v-if="showRule" @close="showRule = false" />
  </scroll-view>
  <!-- 隐私协议 -->
  <!-- <privacyPopup></privacyPopup> -->
</template>

  <script setup>
import {
  onLoad,
  onShow,
  onUnload,
  onHide,
  onShareAppMessage,
} from "@dcloudio/uni-app";
import { ref } from "vue";
import { oss2, message, debounce, generateSign2 } from "@/utils/utils";
import RulePopup from "./components/rule-popup.vue";
import { userLogin } from "@/services/utils";
import privacyPopup from "@/components/privacy-popup";

let enterTime = "";
let outTime = "";
let stayTime = "";
let scanStauts = {
  4001: { img: "code_wait.png", btn: "ultraman_campaign_scan_nonactivated" },
  4002: { img: "code_past.png", btn: "ultraman_campaign_scan_invalid" },
  4000: {
    img: "code_err.png",
    btn: "ultraman_campaign_scan_anomaly",
  },
};
let emdlzMap = {
  活动中: "campaign_landing_page",
  未开始: "campaign_ready_page",
  已结束: "campaign_end_page",
  繁忙: "campaign_system_busy_page",
};

const activityStatus = ref("已结束");
const iAgree = ref(false);
const showRule = ref(false);
const showCard = ref(false);

const memberId = ref("");
const code = ref("");
const showDialog = ref(false);
const dialogCode = ref(0);
const dialogBg = ref("");

onLoad(async (query) => {
  if (activityStatus !== "未开始") {
    uni.login({
      provider: "weixin",
      success: async (res) => {
        const loginParam = {
          type: 1,
        };
        loginParam.code = res.code;

        const { data } = await userLogin(loginParam);
        uni.setStorageSync("OPENID", data?.openId);
        uni.setStorageSync("UNIONID", data?.unionId);
        uni.setStorageSync("TOKEN", data?.accessToken);
        getApp().emdlz2("set", "user", "openid", data.openId);
        getApp().emdlz2("set", "user", "unionId", data.unionId);
        getApp().getUserInfo();

        const pages = getCurrentPages();
        const beforePage = pages[pages.length - 2]?.route ?? "";
        if (beforePage !== "pages/home/home") {
          const codeValue = decodeURIComponent(
            query.q ? query.q : uni.getLaunchOptionsSync().query.q
          );
          code.value = codeValue.split("/")[codeValue.split("/").length - 1];
          if (code.value !== "undefined") {
            const body = {
              userValue: uni.getStorageSync("OPENID"),
              qrCode: code.value,
              source: "mini",
              timestamp: Date.parse(new Date()),
            };
            scanCodeIn(body);
          }
        }

        getCardInfo();
      },
    });
  }
});
onShow(() => {
  // 用户进入时间
  enterTime = new Date();

  getApp().accessLogAdd();
  if (uni.getStorageSync("ULTRAMANAGREE")) {
    iAgree.value = uni.getStorageSync("ULTRAMANAGREE");
  }
});
onHide(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime?.getTime() - enterTime?.getTime()) / 1000;
  getApp().emdlz2(
    "track",
    "event",
    "ultraman_" + emdlzMap[activityStatus.value],
    "view",
    emdlzMap[activityStatus.value],
    stayTime
  );
});
onUnload(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime?.getTime() - enterTime?.getTime()) / 1000;
  getApp().emdlz2(
    "track",
    "event",
    "ultraman_campaign_landing_page",
    "view",
    "campaign_landing_page",
    stayTime
  );
});

const linkTo = (url) => uni.navigateTo({ url });

const getCardInfo = () => {
  const body = {
    userValue: uni.getStorageSync("OPENID"),
    timestamp: Date.parse(new Date()),
  };
  uni.request({
    url: process.env.ALTRAMAN_URL + `/zex-draw/api/card/getNewFlag`,
    method: "get",
    data: {
      ...body,
      ...{ sign: generateSign2(body) },
    },
    success: function (res) {
      if (res.data.code === 200) {
        if (res.data.response.isNew === 0) {
          showCard.value = false;
        } else {
          showCard.value = true;
        }
      } else {
        uni.showToast({
          title: res.data.message,
          icon: "none",
          duration: 2000,
        });
      }
    },
    fail: function (err) {},
  });
};
const backHome = () => {
  getApp().emdlz2(
    "track",
    "event",
    "ultraman_" + emdlzMap[activityStatus.value],
    "click",
    "return_to_previous_page",
    ""
  );
  uni.switchTab({
    url: "/pages/home/home",
  });
};

const scanCodeIn = debounce(
  async (body) => {
    uni.request({
      url: `${process.env.ALTRAMAN_URL}/zex-qr/api/qr/validation`,
      method: "get",
      data: {
        ...body,
        ...{ sign: generateSign2(body) },
      },

      success: async (requestRes) => {
        getApp()
          .getUserInfo()
          .then((user) => {
            memberId.value = user.memberScore.memberId;

            if (requestRes.data.code === 200) {
              // linkTo(
              //   `/campaign/pages/ultraman/webview?accesstoken=${uni.getStorageSync(
              //     "TOKEN"
              //   )}&code=${code.value}&openid=${uni.getStorageSync(
              //     "OPENID"
              //   )}&unionid=${uni.getStorageSync("UNIONID")}&memberid=${
              //     user.memberScore.memberId
              //   }&agree=${uni.getStorageSync("ULTRAMANAGREE")}`
              // );
              // code.value = "";
            } else if ([4000].includes(requestRes.data.code)) {
              code.value = "";
              dialogCode.value = 4000;
              dialogBg.value = scanStauts[4000].img;
              showDialog.value = true;
            } else if ([4001].includes(requestRes.data.code)) {
              code.value = "";
              dialogCode.value = 4001;
              dialogBg.value = scanStauts[4001].img;
              showDialog.value = true;
            } else if ([4002].includes(requestRes.data.code)) {
              code.value = "";
              dialogCode.value = 4002;
              dialogBg.value = scanStauts[4002].img;
              showDialog.value = true;
            } else {
              code.value = "";
              uni.showToast({
                title: requestRes.data.message,
                icon: "none",
                duration: 2000,
              });
            }
          });
        // if (requestRes.data.code === 200) {
        //   // getApp()
        //   //   .getUserInfo()
        //   //   .then((user) => {
        //   linkTo(
        //     `/campaign/pages/ultraman/webview?accesstoken=${uni.getStorageSync(
        //       "TOKEN"
        //     )}&code=${code.value}&openid=${uni.getStorageSync(
        //       "OPENID"
        //     )}&unionid=${uni.getStorageSync("UNIONID")}&memberid=${
        //       user.memberScore.memberId
        //     }&agree=${uni.getStorageSync("ULTRAMANAGREE")}`
        //   );
        //   code.value = "";
        //   // });
        // } else if ([4000].includes(requestRes.data.code)) {
        //   code.value = "";
        //   dialogCode.value = 4000;
        //   dialogBg.value = scanStauts[4000].img;
        //   showDialog.value = true;
        // } else if ([4001].includes(requestRes.data.code)) {
        //   code.value = "";
        //   dialogCode.value = 4001;
        //   dialogBg.value = scanStauts[4001].img;
        //   showDialog.value = true;
        // } else if ([4002].includes(requestRes.data.code)) {
        //   code.value = "";
        //   dialogCode.value = 4002;
        //   dialogBg.value = scanStauts[4002].img;
        //   showDialog.value = true;
        // } else {
        //   code.value = "";
        //   uni.showToast({
        //     title: requestRes.data.message,
        //     icon: "none",
        //     duration: 2000,
        //   });
        // }
      },
      fail(requestErr) {
        code.value = "";
        uni.showToast({
          title: requestErr.data.message,
          icon: "none",
          duration: 2000,
        });
      },
    });
  },
  500,
  false
);

const toScanCode = () => {
  getApp().emdlz2(
    "track",
    "event",
    "ultraman_campaign_landing_page",
    "click",
    "go_scan",
    ""
  );
  if (!iAgree.value) return message("请先同意相关协议!");
  uni.scanCode({
    scanType: ["qrCode"],
    success: async (res) => {
      console.log(res);
      code.value = res.result.split("/")[res.result.split("/").length - 1];
      console.log(res.result.split("/"));

      const body = {
        userValue: uni.getStorageSync("OPENID"),
        qrCode: code.value,
        source: "mini",
        timestamp: Date.parse(new Date()),
      };
      uni.request({
        url: `${process.env.ALTRAMAN_URL}/zex-qr/api/qr/validation`,
        method: "get",
        data: {
          ...body,
          ...{ sign: generateSign2(body) },
        },

        success: async (requestRes) => {
          if (requestRes.data.code === 200) {
            // 是否登录注册
            if (!uni.getStorageSync("TOKEN")) {
              // 静默拿取微信用户的 openId 与 unionId 信息
              uni.login({
                provider: "weixin",
                success: async (res) => {
                  console.log(res);
                  const loginParam = {
                    type: 1,
                  };
                  loginParam.code = res.code;
                  const { data } = await userLogin(loginParam);
                  uni.setStorageSync("TOKEN", data?.accessToken);
                  uni.setStorageSync("OPENID", data?.openId);
                  uni.setStorageSync("UNIONID", data?.unionId);
                  getApp().emdlz2("set", "user", "openid", data?.openId);
                  getApp().emdlz2("set", "user", "unionId", data?.unionId);

                  // linkTo(
                  //   `/campaign/pages/ultraman/webview?accesstoken=${uni.getStorageSync(
                  //     "TOKEN"
                  //   )}&code=${code.value}&openid=${uni.getStorageSync(
                  //     "OPENID"
                  //   )}&unionid=${uni.getStorageSync("UNIONID")}&memberid=${
                  //     getApp().globalData.user.memberScore.memberId
                  //   }&agree=${uni.getStorageSync("ULTRAMANAGREE")}`
                  // );
                  // code.value = "";
                },
              });
            } else {
              // linkTo(
              //   `/campaign/pages/ultraman/webview?accesstoken=${uni.getStorageSync(
              //     "TOKEN"
              //   )}&code=${code.value}&openid=${uni.getStorageSync(
              //     "OPENID"
              //   )}&unionid=${uni.getStorageSync("UNIONID")}&memberid=${
              //     getApp().globalData.user.memberScore.memberId
              //   }&agree=${uni.getStorageSync("ULTRAMANAGREE")}`
              // );
              // code.value = "";
            }
          } else if ([4000].includes(requestRes.data.code)) {
            code.value = "";
            dialogCode.value = 4000;
            dialogBg.value = scanStauts[4000].img;
            showDialog.value = true;
          } else if ([4001].includes(requestRes.data.code)) {
            code.value = "";
            dialogCode.value = 4001;
            dialogBg.value = scanStauts[4001].img;
            showDialog.value = true;
          } else if ([4002].includes(requestRes.data.code)) {
            code.value = "";
            dialogCode.value = 4002;
            dialogBg.value = scanStauts[4002].img;
            showDialog.value = true;
          } else {
            code.value = "";
            uni.showToast({
              title: requestRes.data.message,
              icon: "none",
              duration: 2000,
            });
          }
        },
        fail(requestErr) {
          code.value = "";
          uni.showToast({
            title: requestErr.data.message,
            icon: "none",
            duration: 2000,
          });
        },
      });
    },
    fail(err) {
      console.log(err);
    },
  });
};

const toPurchase = () => {
  getApp().emdlz2(
    "track",
    "event",
    "ultraman_campaign_landing_page",
    "click",
    "go_purchase",
    ""
  );
  uni.switchTab({
    url: "/pages/home/home",
  });
};
const toInput = () => {
  getApp().emdlz(
    "track",
    "event",
    "ultraman_campaign_landing_page",
    "click",
    "manual_redeem",
    ""
  );
  if (!iAgree.value) return message("请先同意相关协议!");
  linkTo("/campaign/pages/ultraman/scanCodeInput");
};
const toPrize = () => {
  getApp().emdlz(
    "track",
    "event",
    "ultraman_campaign_landing_page",
    "click",
    "check_prize",
    ""
  );

  if (!iAgree.value) return message("请先同意相关协议!");
  linkTo(
    `/campaign/pages/ultraman/prizeWebview?accesstoken=${uni.getStorageSync(
      "TOKEN"
    )}&openid=${uni.getStorageSync("OPENID")}&unionid=${uni.getStorageSync(
      "UNIONID"
    )}&memberid=${
      getApp().globalData.user.memberScore.memberId
        ? getApp().globalData.user.memberScore.memberId
        : memberId.value
    }&agree=${uni.getStorageSync("ULTRAMANAGREE")}`
  );
};
const toCard = () => {
  getApp().emdlz(
    "track",
    "event",
    "ultraman_campaign_landing_page",
    "click",
    "check_collection",
    ""
  );
  if (!iAgree.value) return message("请先同意相关协议!");
  linkTo(
    `/campaign/pages/ultraman/cardWebview?accesstoken=${uni.getStorageSync(
      "TOKEN"
    )}&openid=${uni.getStorageSync("OPENID")}&unionid=${uni.getStorageSync(
      "UNIONID"
    )}&memberid=${
      getApp().globalData.user.memberScore.memberId
        ? getApp().globalData.user.memberScore.memberId
        : memberId.value
    }&agree=${uni.getStorageSync("ULTRAMANAGREE")}`
  );
};

const doAgree = () => {
  getApp().emdlz(
    "track",
    "event",
    "ultraman_campaign_landing_page",
    "click",
    "check_box",
    ""
  );
  iAgree.value = !iAgree.value;
  uni.setStorageSync("ULTRAMANAGREE", iAgree.value);
};
const openRule = () => {
  getApp().emdlz(
    "track",
    "event",
    "ultraman_campaign_landing_page",
    "click",
    "check_activity_rule1",
    ""
  );
  showRule.value = true;
};
const openRule2 = () => {
  getApp().emdlz(
    "track",
    "event",
    "ultraman_campaign_landing_page",
    "click",
    "check_activity_rule2",
    ""
  );
  showRule.value = true;
};
const openRule3 = () => {
  getApp().emdlz(
    "track",
    "event",
    scanStauts[dialogCode.value].btn,
    "click",
    "check_activity_rule",
    ""
  );
  showRule.value = true;
};
const dialogClose = () => {
  getApp().emdlz(
    "track",
    "event",
    scanStauts[dialogCode.value].btn,
    "click",
    "pop_up_close",
    ""
  );
  showDialog.value = false;
};
const dialogBack = () => {
  getApp().emdlz(
    "track",
    "event",
    scanStauts[dialogCode.value].btn,
    "click",
    "pop_up_return",
    ""
  );
  showDialog.value = false;
};

onShareAppMessage((e) => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  console.log(currentPage);
  const pageUrl = currentPage.$page.fullPath;

  const shareObj = {
    title: "打开迷你奥利奥，扫码互动赢奥特曼大奖，还可集图鉴兑更多好礼！", // 默认是小程序的名称(可以写slogan等)
    path: pageUrl + `?from=pubid:shareback;aid:sharecard`, // 默认是当前页面，必须是以‘/’开头的完整路径
    imageUrl: oss2("others/ultraman/share_ultraman.jpg"), //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
    success: (res) => {
      // 转发成功之后的回调
      if (res.errMsg == "shareAppMessage:ok") {
      }
    },
    fail: (err) => {
      // 转发失败之后的回调
      console.log("转发失败之后的回调", err);
      if (res.errMsg == "shareAppMessage:fail cancel") {
        // 用户取消转发
        console.log("用户取消转发");
      } else if (res.errMsg == "shareAppMessage:fail") {
        // 转发失败，其中 detail message 为详细失败信息
        console.log("转发失败，其中detail message 为详细失败信息");
      }
    },
    complete: () => {
      // 转发结束之后的回调（转发成不成功都会执行）
      console.log("转发结束之后的回调（转发成不成功都会执行）");
    },
  };
  console.log(shareObj);
  return shareObj;
});
</script>

  <style>
page {
  background-color: #08204e !important;
}
</style>
  <style lang="less" scoped>
@import "@/static/css/theme.less";

.puzzle {
  height: 1448rpx !important;
}
.ultraman-container {
  position: relative;
  width: 100%;
  min-height: 724px;
  height: 100vh;
  background-color: #08204e;
  background-repeat: no-repeat;
  background-position: top left;
  background-size: 375px 812px;
  .icon_btn {
    width: 50px;
    height: 53px;
    position: absolute;
    right: 15px;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 50px 100%;
    .signal {
      position: absolute;
      right: 12px;
      bottom: 17px;
      width: 7px;
      height: 6px;
      background: #db0000;
      border-radius: 50%;
    }
  }
  .rule_icon {
    top: 22px;
  }
  .prize_icon {
    top: 71px;
  }
  .card_icon {
    top: 120px;
  }
  .ultraman_sign {
    width: 75px;
    height: 8px;
    position: absolute;
    left: 150px;
    top: 716px;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 100% 100%;
  }

  .index_btn {
    width: 168px;
    height: 58px;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 168px 100%;
    position: absolute;
    left: 103px;
  }
  .code_btn {
    top: 548px;
  }
  .buy_btn {
    top: 607px;
  }
  .backHomeBtn {
    position: absolute;
    bottom: 25px;
    left: 79px;
    width: 218px;
    height: 58px;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 218px 100%;
  }
  .code_hint {
    width: 100%;
    height: 11px;
    font-size: 10px;
    font-family: FZLTHJW;
    color: #fff;
    position: absolute;
    left: 0;
    top: 670px;
  }
  .code_text {
    width: 100%;
    height: 10px;
    font-size: 8px;
    font-family: FZZhunYuan-M02S;
    color: #fff;
    font-weight: 400;
    text-align: center;
    position: absolute;
    left: 0;
    top: 683px;
  }
  .agree {
    width: 100%;
    font-size: 10px;
    font-family: FZLTHJW;
    color: #fff;
    box-sizing: border-box;
    z-index: 10;
    position: absolute;
    left: 0;
    top: 697px;

    .agree-content {
      display: flex;
      word-break: break-all;
    }

    .i-agree {
      position: relative;
      width: 12px;
      height: 12px;
      background-color: transparent;
      margin-right: 10px;
      box-sizing: border-box;
      border: 2px solid #fff;
      image {
        position: absolute;
        top: -2px;
        left: 0;
        width: 12px;
        height: 12px;
      }
    }
  }
  .text_link {
    color: #3da2ff;
    text-decoration: underline;
  }
}

.mode {
  width: 100%;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 90;
  background-color: rgba(10, 28, 108, 0.7);
  .Dialog_body {
    position: absolute;
    min-height: 384px;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 100% 100%;
    .Dialog_close {
      position: absolute;
      top: 42px;
      right: 60px;
      width: 33px;
      height: 33px;
      background-color: transparent;
    }
    .Dialog_back,
    .Dialog_rule {
      position: absolute;
      background-repeat: no-repeat;
      background-position: top left;
      background-size: 100% 100%;
    }
  }
}
</style>

